package com.gaojinqi.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author gaojinqi
 * @date 2019/6/1 13:07
 */
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    // 超时配置
    /*@HystrixCommand(commandProperties = {
            // 设置超时时间，默认1000
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })*/
    // 熔断
    @HystrixCommand(commandProperties = {
            // 是否开启熔断器，默认true
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            // 当在配置时间窗口内达到此数量的失败后，进行短路。默认20个
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            // 短路多久以后开始尝试是否恢复，默认5s
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            // 出错百分比阈值，当达到此阈值后，开始短路。默认50%
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })
    @GetMapping("/getProductInfoList")
    public String getProductInfoList(@RequestParam("number") Integer number) {
        if (number == 1) {
            return "成功";
        }
        // 模拟超时服务
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForObject("http://127.0.0.1:8091/product/listForOrder",
                Arrays.asList("164103465734242707"),
                String.class);
        // 模拟服务不可用
        //throw new RuntimeException();
    }

    /**
     * 降级时调用，回调函数
     */
    private String fallback() {
        return "太拥挤了，请稍后再试~~";
    }

    /**
     * 降级时调用，默认回调函数
     */
    private String defaultFallback() {
        return "默认提示：太拥挤了，请稍后再试~~";
    }
}
